package com.cyou.gamehistory.admin.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cyou.framework.util.StringUtility;
import com.cyou.gamehistory.entity.Manager;
import com.cyou.gamehistory.service.ManagerService;
import com.cyou.gamehistory.util.ApplicationConstants;
import com.cyou.gamehistory.util.WebUtil;
import com.sun.mail.iap.Response;


/**
 * 
 * @author wangzhang
 * date 2012-12-19 下午1:18:40
 */
@Controller
@RequestMapping(value="/a")
public class ManagerController {
	@Autowired
	private ManagerService managerService;
	@RequestMapping(value = { "", "login" })
	public String login(Model model,String username,String password,HttpSession session,HttpServletRequest request){
		if(username==null && password==null){
			return "admin/login";
		}
		Manager manager=managerService.getManager(username, password);
		if(manager==null){
			model.addAttribute("error", "用户名或密码错误");
			return "admin/login";
		}
		session.setAttribute(ApplicationConstants.ADMIN_SESSION_MANAGER, manager);
		session.setAttribute("loginTime", manager.getLoginTime());
		session.setAttribute("loginIp", manager.getLoginIp());
		String loginTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String loginIp=WebUtil.getIpAddr(request);
		manager.setLoginIp(loginIp);
		manager.setLoginTime(loginTime);
		managerService.updateManager(manager);
		
		
		
		return "redirect:/a/gamehistory/list";
	}
	@RequestMapping("/manager/modify")
	public void modifyPassword(HttpServletResponse response,Model model,HttpSession session ,String originalPass,String newPass,String confirmPass) throws IOException{
		Manager manager=(Manager) session.getAttribute(ApplicationConstants.ADMIN_SESSION_MANAGER);
		if(StringUtility.isNotBlank(originalPass)&&!originalPass.endsWith(manager.getPassword())){
			//model.addAttribute("error", "原密码错误");
			response.getWriter().print("原密码错误");
			return ;
			//session.removeAttribute(ApplicationConstants.ADMIN_SESSION_MANAGER);
			//return "admin/login";
		}
		manager.setPassword(newPass);
		managerService.updateManager(manager);
		//model.addAttribute("success", "修改成功");
		//return "admin/login";
		response.getWriter().print("修改成功");
	}
	@RequestMapping("/manager/exit")
	public String exit(HttpSession session){
		session.removeAttribute(ApplicationConstants.ADMIN_SESSION_MANAGER);
		return "admin/login";
	}
}
